import numpy as np
from matplotlib import pyplot as plt

num = 20
xi = np.linspace(0, 10, num)
yi = -4 * xi + 4 + np.random.uniform(-3, 3, num)
# y = -4x + 4
plt.figure()
plt.scatter(xi, yi)

lr = 0.004
#最小化损失函数有俩种方法，最小二乘法和梯度下降法
w = 0
b = 0
count = 4000
for i in range(count):
    w1 = 0
    b1 = 0
    for j in range(num):
        w1 += (w * xi[j] + b - yi[j]) * xi[j]
        b1 += w * xi[j] + b - yi[j]
    w1 = w1 / num
    b1 = b1 / num
    w -= lr * w1
    b -= lr * b1

plt_x = np.linspace(0, 10, 20)
plt_y = w * plt_x + b
plt.plot(plt_x, plt_y, color='r')

print(w, b)

plt.show()